package locking;

import junit.framework.TestCase;
import net.pimpas.locking.entity.serviceprovider.EntityLockingServiceProvider;
import net.pimpas.locking.entity.serviceprovider.EntityLockingServiceProviderFactoryImpl;
import net.pimpas.locking.serviceprovider.LockingServiceProvider;
import net.pimpas.locking.serviceprovider.LockingServiceProviderFactoryImpl;
import net.pimpas.persistence.hibernate.serviceprovider.HibernateServiceProviderFactoryImpl;

import org.hibernate.Session;

import entitys.Food;

public class EntityLock extends TestCase {
	final static Session s = HibernateServiceProviderFactoryImpl.
	getPersistenceServiceProvider().getSessionFactory().openSession();
	final static EntityLockingServiceProvider locker = 
		EntityLockingServiceProviderFactoryImpl.getEntityLockingServiceProvider();
	
	@Override
	protected void setUp() throws Exception {
		Food meat = new Food();
		meat.setDescricao("meat");
		s.beginTransaction();
		
		s.persist(meat);
		s.getTransaction().commit();
		
		s.beginTransaction();
	}
	
	public void testLock( ) {
		Food meat = (Food) s.get(Food.class, new Long(1));
		locker.lockWrite(meat);
		meat.setDescricao("meatX");
		s.saveOrUpdate(meat);
		s.getTransaction().commit();
		
		final LockingServiceProvider l = 
			LockingServiceProviderFactoryImpl.getLockingServiceProvider();
		final Object ob = new Object();
		
		new Thread() {
		
			@Override
			public void run() {
				l.lockWrite(ob);
				Session sx = HibernateServiceProviderFactoryImpl.
				getPersistenceServiceProvider().getSessionFactory().openSession();
				sx.beginTransaction();
				Food f = (Food) sx.get(Food.class, new Long(1));
				locker.lockRead(f);
				locker.unlockRead(f);
				locker.lockWrite(f);
				f.setDescricao("meatY");
				sx.saveOrUpdate(f);
				System.out.println(f.getDescricao());
				l.unlockWrite(ob);
				sx.getTransaction().commit();
				sx.flush();
				sx.close();
			}
		
		}.start();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		locker.unlockWrite(meat);
		l.lockWrite(ob);
		l.unlockWrite(ob);
		s.close();
	}
	
	@Override
	protected void tearDown() throws Exception {
		Session sx = HibernateServiceProviderFactoryImpl.
		getPersistenceServiceProvider().getSessionFactory().openSession();
		Food f = (Food) sx.get(Food.class, new Long(1));
		System.out.println(f.getDescricao());
		sx.close();
	}
}